package com.tanhua.server.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.VisitorsApi;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.dubbo.server.pojo.Visitors;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.pojo.User;
import com.tanhua.server.pojo.UserInfo;
import com.tanhua.server.utils.RelativeDateFormat;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.Movements;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.PicUploadResult;
import com.tanhua.server.vo.VisitorsVo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

@Service
public class MovementsService {

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    @Autowired
    private PicUploadService picUploadService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Reference(version = "1.0.0")
    private VisitorsApi visitorsApi;

    /**
     * 发布动态
     *
     * @param textContent
     * @param location
     * @param longitude
     * @param latitude
     * @param multipartFiles
     * @return
     */
    public String saveMovements(String textContent,
                                String location,
                                String longitude, String latitude,
                                MultipartFile[] multipartFiles) {
        User user = UserThreadLocal.get();

        Publish publish = new Publish();
        publish.setUserId(user.getId());
        publish.setText(textContent);
        publish.setLocationName(location);
        publish.setLongitude(longitude);
        publish.setLatitude(latitude);
        //图片上传
        List<String> imageUrls = new ArrayList<>();
        for (MultipartFile file : multipartFiles) {
            PicUploadResult uploadResult = picUploadService.upload(file);
            imageUrls.add(uploadResult.getName());
        }
        publish.setMedias(imageUrls);
        publish.setCreated(System.currentTimeMillis());
        publish = quanZiApi.savePublish(publish);
        if (publish.getId() != null) {
            return publish.getId().toHexString();
        }
        return null;
    }

    /**
     * 查询好友的动态信息及推荐信息
     *
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult queryPublishList(Integer page, Integer pagesize, Integer logo) {
        PageResult pageResult = new PageResult();
        User user = UserThreadLocal.get();
        Long id = user.getId();
        PageInfo<Publish> pageInfo = null;

        if (logo != null) {
            //查询推荐动态
            user.setId(null);
        }

        pageInfo = quanZiApi.queryPublishList(user.getId(), page, pagesize);

        pageResult.setCounts(0);
        pageResult.setPages(0);
        pageResult.setPage(page);
        pageResult.setPagesize(pagesize);

        if (logo != null) {
            //查询推荐动态
            String key = "QUANZI_PUBLISH_RECOMMEND_" + id;
            String value = redisTemplate.opsForValue().get(key);
            if (StringUtils.isNotEmpty(value)) {
                //命中了数据
                String[] pids = StringUtils.split(value, ",");
                int startIndex = (page - 1) * pagesize;
                if (startIndex < pids.length) {
                    int endIndex = startIndex + pagesize - 1;
                    if (endIndex >= pids.length) {
                        endIndex = pids.length;
                    }
                    Set<Long> pidList = new HashSet<>();
                    for (int i = startIndex; i <= endIndex; i++) {
                        pidList.add(Long.valueOf(pids[i]));
                    }
                    List<Publish> publishList = quanZiApi.queryPublishByPids(pidList);
                    //最后查到的推荐动态不为空就赋值,否则还是默认推荐
                    if (publishList != null) {
                        pageInfo = new PageInfo<>();
                        pageInfo.setRecords(publishList);
                    }
                }
            }
        }

        List<Publish> records = pageInfo.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            //没有查询到动态数据,直接返回
            return pageResult;
        }

        List<Movements> movementsList = fillValueToMovements(records);

        pageResult.setItems(movementsList);

        return pageResult;
    }

    private List<Movements> fillValueToMovements(List<Publish> records) {
        User user = UserThreadLocal.get();

        List<Movements> movementsList = new ArrayList<>();
        Set<Long> userIds = new HashSet<>();
        for (Publish record : records) {
            Movements movements = new Movements();
            movements.setId(record.getId().toHexString());
            movements.setUserId(record.getUserId());

            userIds.add(record.getUserId());

            movements.setTextContent(record.getText());
            movements.setImageContent(record.getMedias().toArray(new String[]{}));
            movements.setCreateDate(RelativeDateFormat.format(new Date(record.getCreated())));

            String likeCommentKey1 = "QUANZI_COMMENT_LIKE_USER_" + user.getId() + "_" + record.getId();
            movements.setHasLiked(redisTemplate.hasKey(likeCommentKey1) ? 1 : 0);
            String likeCommentKey = "QUANZI_COMMENT_LIKE_" + record.getId();
            String s = redisTemplate.opsForValue().get(likeCommentKey);
            if (!StringUtils.isEmpty(s)) {
                movements.setLikeCount(Integer.valueOf(s));
            } else {
                movements.setLikeCount(0);
            }

            String loveCommentKey1 = "QUANZI_COMMENT_LOVE_USER_" + user.getId() + "_" + record.getId();
            movements.setHasLoved(redisTemplate.hasKey(loveCommentKey1) ? 1 : 0);
            String loveCommentKey = "QUANZI_COMMENT_LOVE_" + record.getId();
            String s1 = redisTemplate.opsForValue().get(loveCommentKey);
            if (!StringUtils.isEmpty(s1)) {
                movements.setLoveCount(Integer.valueOf(s1));
            } else {
                movements.setLoveCount(0);
            }

            movements.setDistance("1.2公里");     //TODO
            movements.setCommentCount(30);
            movementsList.add(movements);
        }

        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
        userInfoQueryWrapper.in("user_id", userIds);
        List<UserInfo> userInfoList = userInfoService.queryUserInfoList(userInfoQueryWrapper);
        for (Movements movements : movementsList) {
            for (UserInfo userInfo : userInfoList) {
                if (movements.getUserId().longValue() == userInfo.getUserId().longValue()) {
                    movements.setTags(StringUtils.split(userInfo.getTags(), ","));
                    movements.setNickname(userInfo.getNickName());
                    movements.setGender(userInfo.getSex().name().toLowerCase());
                    movements.setAvatar(userInfo.getLogo());
                    movements.setAge(userInfo.getAge());
                    break;
                }
            }
        }
        return movementsList;
    }

    public Long likeComment(String publishId) {
        User user = UserThreadLocal.get();
        boolean b = quanZiApi.saveLikeComment(user.getId(), publishId);
        if (!b) {
            //保存失败
            return null;
        }
        //保存成功,获取点赞数
        String likeCommentKey = "QUANZI_COMMENT_LIKE_" + publishId;
        Long likecount = 0L;
        if (!redisTemplate.hasKey(likeCommentKey)) {
            likecount = quanZiApi.queryCommentCount(publishId, 1);
            redisTemplate.opsForValue().set(likeCommentKey, String.valueOf(likecount));
        } else {
            likecount = redisTemplate.opsForValue().increment(likeCommentKey);
        }
        //记录当前用户已经点赞
        String likeCommentKey1 = "QUANZI_COMMENT_LIKE_USER_" + user.getId() + "_" + publishId;
        redisTemplate.opsForValue().set(likeCommentKey1, "1");
        return likecount;
    }

    public Long dislikeComment(String publishId) {
        User user = UserThreadLocal.get();
        boolean b = quanZiApi.removeComment(user.getId(), publishId, 1);
        if (!b) {
            return null;
        }
        //redis中的点赞数-1
        String likeCommentKey = "QUANZI_COMMENT_LIKE_" + publishId;
        Long count = redisTemplate.opsForValue().decrement(likeCommentKey);
        //删除改用户的标记点赞
        String likeCommentKey1 = "QUANZI_COMMENT_LIKE_USER_" + user.getId() + "_" + publishId;
        redisTemplate.delete(likeCommentKey1);
        return count;
    }

    public Long loveComment(String publishId) {
        User user = UserThreadLocal.get();
        boolean b = quanZiApi.saveLoveComment(user.getId(), publishId);
        if (!b) {
            //保存失败
            return null;
        }
        //保存成功,获取喜欢数
        String loveCommentKey = "QUANZI_COMMENT_LOVE_" + publishId;
        Long lovecount = 0L;
        if (!redisTemplate.hasKey(loveCommentKey)) {
            lovecount = quanZiApi.queryCommentCount(publishId, 3);
            redisTemplate.opsForValue().set(loveCommentKey, String.valueOf(lovecount));
        } else {
            lovecount = redisTemplate.opsForValue().increment(loveCommentKey);
        }
        //记录当前用户已经喜欢
        String loveCommentKey1 = "QUANZI_COMMENT_LOVE_USER_" + user.getId() + "_" + publishId;
        redisTemplate.opsForValue().set(loveCommentKey1, "1");
        return lovecount;
    }

    public Long unloveComment(String publishId) {
        User user = UserThreadLocal.get();
        boolean b = quanZiApi.removeComment(user.getId(), publishId, 3);
        if (!b) {
            return null;
        }
        //redis中的喜欢数-1
        String loveCommentKey = "QUANZI_COMMENT_LOVE_" + publishId;
        Long count = redisTemplate.opsForValue().decrement(loveCommentKey);
        //删除改用户的标记喜欢
        String loveCommentKey1 = "QUANZI_COMMENT_LOVE_USER_" + user.getId() + "_" + publishId;
        redisTemplate.delete(loveCommentKey1);
        return count;
    }

    public Movements queryMovementsById(String publishId) {
        Publish publish = quanZiApi.queryPublishById(publishId);
        if (null == publish) {
            return null;
        }
        //查询到动态数据,进行数据填充
        List<Publish> redos = new ArrayList<>();
        redos.add(publish);
        List<Movements> movementsList = fillValueToMovements(redos);
        Movements movements = movementsList.get(0);
        return movements;
    }

    public List<VisitorsVo> queryVisitorsList() {
        User user = UserThreadLocal.get();
        Long id = user.getId();
        //如果redis中存在上一次查询的时间点就按时间查询,否则就按数量查询
        String redisKey = "visitors_" + id;
        String date = redisTemplate.opsForValue().get(redisKey);
        List<Visitors> visitors = null;
        List<VisitorsVo> visitorsVos = new ArrayList<>();
        if (StringUtils.isEmpty(date)) {
            visitors = visitorsApi.topVisitor(id, 6);
            redisTemplate.opsForValue().set(redisKey, String.valueOf(System.currentTimeMillis()));
        } else {
            visitors = visitorsApi.topVisitor(id, Long.valueOf(date));
            redisTemplate.opsForValue().set(redisKey, String.valueOf(System.currentTimeMillis()));
        }
        if (CollectionUtils.isEmpty(visitors)) {
            return visitorsVos;
        }
        Set<Long> userIds = new HashSet<>();
        for (Visitors visitor : visitors) {
            userIds.add(visitor.getVisitorUserId());
        }
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);
        List<UserInfo> userInfoList = userInfoService.queryUserInfoList(queryWrapper);
        for (Visitors visitor : visitors) {
            for (UserInfo userInfo : userInfoList) {
                if (visitor.getVisitorUserId().longValue() == userInfo.getUserId().longValue()) {
                    VisitorsVo visitorsVo = new VisitorsVo();
                    visitorsVo.setAge(userInfo.getAge());
                    visitorsVo.setAvatar(userInfo.getLogo());
                    visitorsVo.setGender(userInfo.getSex().name().toLowerCase());
                    visitorsVo.setId(userInfo.getUserId());
                    visitorsVo.setNickname(userInfo.getNickName());
                    visitorsVo.setTags(StringUtils.split(userInfo.getTags(), ','));
                    visitorsVo.setFateValue(visitor.getScore().intValue());
                    visitorsVos.add(visitorsVo);
                    break;
                }
            }
        }
        return visitorsVos;
    }

    public PageResult queryAlbumList(Long userId, Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        PageInfo<Publish> albumPageInfo = this.quanZiApi.queryAlbumList(userId, page, pageSize);
        List<Publish> records = albumPageInfo.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return pageResult;
        }
        List<Movements> movementsList = fillValueToMovements(records);
        pageResult.setItems(movementsList);
        return pageResult;
    }
}
